package org.practice.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.practice.model.Account;
import org.practice.model.District;
import org.practice.model.Kindergarten;

/**
 * 使用树的思想解决问题
 * @author jack
 *
 */
public class JSTreeGenerator{
	IPracticeService userService=null;
	
	public JSTreeGenerator(IPracticeService userService){
		this.userService=userService;
	}
	
	/**
	 * [{name:'普陀区',open:'true',target:'right',url:'DistrictAdminManage!doinput.action?district.sysId=om_district000001',icon:'../css/zTreeStyle/img/folder_Open.gif'},nodes:[{},{}]]
	 */
	public String generateDistrictAndKGAdminTreeJs(District district,String districtIcon, String districtUrl,String disAdminUrl, String kgIcon,String kgUrl,String adminIcon,String adminUrl,String target) {
		String districtTreeJs= generateDistrictAdminTreeJs(district,districtIcon,districtUrl,disAdminUrl,target);
		String kindergartenTreeJs=generateKGAdminTreeJs(district,kgIcon,kgUrl,adminIcon,adminUrl, target);
		StringBuffer treeJs=new StringBuffer("["+districtTreeJs);
		if(kindergartenTreeJs.length()>0){
			treeJs.append(","+kindergartenTreeJs);
		}
		treeJs.append("]");
		return treeJs.toString();
	}
	
	private String generateDistrictAdminTreeJs(District district,String icon, String districtUrl, String disAdminUrl, String target){
        List<Account> list=userService.queryDistrictAccount();
		
		StringBuffer districtTreeJs=new StringBuffer("{");
		districtTreeJs.append("name:'"+district.getCompany().getCompanyName()+"',open:'true',target:'"+target+"',url:'"+districtUrl+district.getCompany().getCompanyName()+"',icon:'"+icon+"'");
		if(list.size()>0){
			districtTreeJs.append(",nodes:[");
	       /* for(Account a:list){
	        	districtTreeJs.append("{name:'"+a.getName()+"',open:'true',target:'"+target+"',url:'"+disAdminUrl+""+a.getSysId()+"',icon:'"+icon+"'},");
	        }
	        districtTreeJs.deleteCharAt(districtTreeJs.length()-1);*/
			for (Iterator<Account> it = list.iterator(); it.hasNext();) {
				Account a=it.next();
				districtTreeJs.append("{name:'" + a.getName()+ "',open:'true',target:'" + target + "',url:'"+ disAdminUrl + "" + a.getName() + "',icon:'" + icon+ "'}");
				if (it.hasNext()) {
					districtTreeJs.append(",");
				}
			}
	        districtTreeJs.append("]");
		}
		
		districtTreeJs.append("}");
		
        return districtTreeJs.toString();
	}
	
	
	private String getNodeJsByKG(Kindergarten kg,String kgIcon,String kgUrl,String adminIcon,String adminUrl,String target) {
		StringBuffer sb=new StringBuffer("{");
		sb.append("name:'" + kg.getCompany().getCompanyName() + "',open:'true',icon:'" + kgIcon + "',url:'" + kgUrl + kg.getSysId() + "',target:'" + target + "'");
		if(kg.getChildrenList_VO().size()>0||kg.kgAdminListVo.size()>0){
			sb.append(",nodes:[");
			for (Iterator iterator = kg.getChildrenList_VO().iterator(); iterator.hasNext();) {
				Kindergarten kgg = (Kindergarten) iterator.next();
				sb.append(getNodeJsByKG(kgg,kgIcon,kgUrl,adminIcon,adminUrl,target));//递归树
				if(iterator.hasNext()){
					sb.append(",");
				}
			}
			
			if(kg.getChildrenList_VO().size()>0&&kg.kgAdminListVo.size()>0){
				sb.append(",");
			}
			
			for (Iterator iterator2 = kg.kgAdminListVo.iterator(); iterator2.hasNext();) {
				Account acct = (Account) iterator2.next();
				sb.append("{name:'"+acct.getName()+"',open:'true',icon:'"+adminIcon+"',url:'"+adminUrl+acct.getName()+"',target:'"+target+"'}");
				if(iterator2.hasNext()){
					sb.append(",");
				}
			}
			
			sb.append("]");
		}
		sb.append("}");
		return sb.toString();
	}
	
	
	private String generateKGAdminTreeJs(District district,String kgIcon,String kgUrl, String adminIcon,String adminUrl,String target){
		List<Kindergarten> kglist=userService.queryKindergarten();
		
		List kgAdminList=userService.queryKindergartenAccount();
		for (Iterator iterator = kglist.iterator(); iterator.hasNext();) {
			Kindergarten kindergarten = (Kindergarten) iterator.next();
			kindergarten.kgAdminListVo.addAll(getAdminByKindergarten(kgAdminList,kindergarten.getCompany().getSysId()));
		}
		
		Map kgMap=changeList2Map(kglist);
		StringBuffer sbf=new StringBuffer();
		for (Iterator iterator = kgMap.entrySet().iterator(); iterator.hasNext();) {
			Map.Entry entry = (Map.Entry) iterator.next();
			Kindergarten kg=(Kindergarten)entry.getValue();//kg为树根节点，能过getChildrenList_VO进行关联，构成一颗树
			//getNodeJsByKG(Kindergarten kg,String kgIcon,String kgUrl,String adminIcon,String adminUrl,String target)
			sbf.append(getNodeJsByKG(kg,kgIcon,kgUrl,adminIcon,adminUrl,target));
			if(iterator.hasNext()){
				sbf.append(",");
			}
		}
		return sbf.toString();
        
	}
	
	private List<Account> getAdminByKindergarten(List kgAdminList,String sysId){
		List list=new ArrayList();
		for (Iterator it = kgAdminList.iterator(); it.hasNext();) {
			Account acct = (Account) it.next();
			if(acct.getCompany().getSysId().equals(sysId)){
				list.add(acct);
			}
		}
		return list;
	}
	
	/**
     * 将List组装成树，采用Map为存储结构，依靠关键字depth_FunPO(判断根节点),sysCode_FunPO(判断父子关系)
     * 这里没有用到kindergarten.parentBean判定条件
     */
    private static Map<String,Kindergarten> changeList2Map(List<? extends Kindergarten> orgList){
        Map<String,Kindergarten> resultMap=new LinkedHashMap<String, Kindergarten>();
        for (Iterator<? extends Kindergarten> iterator = orgList.iterator(); iterator.hasNext(); ) {
        	Kindergarten next = iterator.next();
            if(next.getDepth_FunPO()==0){
                resultMap.put(next.getSysId(),next);
            }else{
            	Kindergarten parent=findParent(orgList,next);
                if(parent!=null){
                    parent.getChildrenList_VO().add(next);
                }
            }

        }
        return resultMap;
    }
    
	
    private static Kindergarten findParent(Collection resultMap, Kindergarten children) {
        for (Iterator iterator = resultMap.iterator(); iterator.hasNext(); ) {
        	Kindergarten parent = (Kindergarten) iterator.next();
            if (children.getSysCode_FunPO().length()>0&&parent.getSysCode_FunPO().length()>0) {//避免出现nullpoint
                if(parent.getDepth_FunPO()==children.getDepth_FunPO()-1&&children.getSysCode_FunPO().startsWith(parent.getSysCode_FunPO())){
                    return parent;
                }
            }
        }
        return null;
    }
	
}
